function setCookie(cookieName, cookieValue, lifeTime, path, domain, isSecure){
    document.cookie = escape( cookieName ) + "=" + escape( cookieValue ) +
    ( lifeTime ? ";expires=" + ( new Date( ( new Date() ).getTime() + ( 1000 * lifeTime ) ) ).toGMTString() : "" ) +
    ( path ? ";path=" + path : "") + ( domain ? ";domain=" + domain : "") +
    ( isSecure ? ";secure" : "");
}
function readCookie(cookieName){
    var a_allcookie = document.cookie.split( ';' );
    if(a_allcookie != ''){
            
            for(var i = 0; i < a_allcookie.length; i++){
                
                var key_value = a_allcookie[i].split('=');
                    if(key_value[0] == cookieName){
			return key_value[1];
                    }
		}
            }
    return false;
}

function add_game_to_favourite(thumbnail, title, link, gameid){
    var cookie_key  =   'gamelist[listfavourite_' + gameid +']';
    var item        =   Base64.encode(thumbnail) + '@' + Base64.encode(title) + '@' + Base64.encode(link) + '@' + Base64.encode(gameid);
    setCookie(cookie_key, item, 3600 * 24 * 365, '/', false);
    alert('Đã add game này vào danh sách game yêu thích của bạn (bên phải phía trên)');
    refesh_favouriteList();
}
function refesh_favouriteList(){
    var games   =   _loadFavouriteCookie();
    if(games){
        $('.favourite_menu').fadeIn();
        var html    =   '';
        $('.favourite_menu_list').hide();
        $(games).each(function(index, el){
            var values  =   el.split('@');
            var thumbnail   =   Base64.decode(decodeURIComponent(values[0]));
            var title   =   Base64.decode(decodeURIComponent(values[1]));
            var link    =   Base64.decode(decodeURIComponent(values[2]));
            var id      =   Base64.decode(decodeURIComponent(values[3]));
            
            html        +=   '<div class="dailygame-row favourite_row_' + id +'">';
            html        +=  '<h3><a title="' + title + '" href="' + link + '">';
            html        +=  '<img width="34px" height="34px" alt="' + title + '" src="http://swf.thegioigamevui.com' + thumbnail + '">';
            html        +=  '</a></h3>';
            html        +=  '<p><span>'
            html        +=  '<a title="' + title + '" href="' + link + '">' + title + '</a>';
            html        +=  '<a class="f_remove_game" title="xóa" href="javascript:void(0);" onclick="remove_game_to_favourite(\'' + id + '\')"> [Xóa]</a>';
            html        +=  '</span></p>'
            html        +=  '</div>';
        });
        if(html != '')
        {
            $('.favourite_menu_list').html(html);
            $('.favourite_menu_list').fadeIn();
        }
    }
}
function report_badlink(gameid){
        var data    =   {
            'data[Badlinks][game_id]': gameid
        };
        $.ajax({
          type: 'POST',
          dataType: 'html',
          data: data,
          url: baseUrl + '/badlinks/post',
          success: function(data) {
              alert('Chân thành cám ơn sự đóng góp của bạn! chung tôi sẽ nhanh chóng kiểm tra và khắc phục.');
          }
        });
}
function _loadFavouriteCookie(){
    var a_allcookie = document.cookie.split( ';' );
    var find_favourite_cookie_reg   =   /gamelist/i;
    if(a_allcookie != ''){
        var games=new Array();
        for(var i = 0; i < a_allcookie.length; i++){
            var key_value = a_allcookie[i].split('=');
            if(find_favourite_cookie_reg.test(key_value[0])){
                games.unshift(key_value[1]);
            }            
        }
        if(games.length > 0){
            return games;
        }else{
            return false;
        }
    }
    return false;
}
function remove_game_to_favourite(itemid){
    var cookie_key  =   'gamelist[listfavourite_' + itemid +']';
    setCookie(cookie_key, '', -(3600 * 24 * 365), '/', false);
    $('.favourite_row_' + itemid).fadeOut(1000, function(){
        $('.favourite_row_' + itemid).remove();
        var arr = jQuery.makeArray($('.favourite_menu .dailygame-row'));
        if(arr.length <= 0){
            $('.favourite_menu').fadeOut();
        }
    });
}

function validateEmail(email) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(email);
} 
function tggv_form_alert(input_id, msg){
    var height_input    =   $('#' + input_id).height();
    var width_input     =   $('#' + input_id).width();
    var offset          =   $('#' + input_id).offset();
    
    var html	=	'<div id="form_alert_layer">' + msg + '</div>';
    $('body').append(html);
    $('#form_alert_layer').css({
        'height': 20,
	'display': 'block',
        'font-size': '12px',
        'padding-top': '5px',
        'padding-left': '5px',
        'padding-right': '5px',
        'text-align': 'center',
        'color': '#fff',
        'font-weight': 'bold',
        'background-color': '#2BA104',
	'left': offset.left,
        'position': 'absolute',
	'top': offset.top - height_input - 5
    });
     $('#' + input_id).focus();
    $('#form_alert_layer').click(function(){
        tggv_hide_form_alert();
    });
    setTimeout(function(){
        tggv_hide_form_alert();
    }, 4000);
}
function tggv_hide_form_alert(){
    if($('#form_alert_layer').attr('id')){
        $('#form_alert_layer').fadeOut(800, function(){
            $('#form_alert_layer').remove();
        });
    }
}
/** show play game on full screen */
function show_fullscreen(){
    show_screen_waitting();
    $('.playgame-fullscreen').show();
    var document_width  =   $(window).width();
    var document_height  =   $(window).height();
    $('.playgame-fullscreen').css({
        'left': (document_width - $('.playgame-fullscreen').width())/ 2,
        'top': 0
    });
    
    $('.Playgame-content' ).css({
        'display': 'none'
    });
    
}
function close_fullscreen(){
    $('.playgame-fullscreen').hide();
    
    $('.Playgame-content' ).css({
        'display': 'block'
    });
    
    close_screen_waitting();
}
function show_screen_waitting(){
	var width	=	$(document).width();
	var height	=	$(document).height();

	var html	=	'<div class="ajax_loader_layer" id="screen_waitting">\b</div>';
	$('body').append(html);
        if ( $.browser.msie ) {
            $('#screen_waitting').css({
                'filter': 'alpha(opacity = 40)'
            });
        }
	$('#screen_waitting').css({
		'width' : width,
		'height' : height,
		'display': 'block',
		'left': 0,
                'z-index': 999,
                'position': 'absolute',
		'top': 0
	});
}
function close_screen_waitting(){
    $('#screen_waitting').remove();
}

/** email newsletter */
function submit_newsletter(){
    var email   =   $('#email-news-letter').val();
    if(!validateEmail(email)){
        tggv_form_alert('email-news-letter', 'Vui lòng nhập 1 email hợp lệ');
        $('#email-news-letter').focus();
        return;
    }
    
    $.ajax({
          type: 'POST',
          data: {email: email},
          dataType: 'html',
          url: baseUrl + '/newsletters/add',
          success: function(data) {
             alert('Bạn đã đăng ký nhận email thành công');
             $('#email-news-letter').val('');
          }
   });
}
/** email newsletter */

/** contact form */
function submit_contact(){
    if($('#txtfullname').val()== ''){
        tggv_form_alert('txtfullname', 'Vui lòng nhập họ tên');
        return;
    }
    if(!validateEmail($('#txtemail').val())){
        tggv_form_alert('txtemail', 'Vui lòng nhập 1 email hợp lệ');
        return;
    }
    if($('#recaptcha_response_field').val() == ''){
        tggv_form_alert('recaptcha_response_field', 'Vui lòng nhập mã bảo vệ bạn nhìn thấy trong hình bên dưới');
        return;
    }
    $('#frmContact').submit();
}
function reset_contact(){
    $('#txtfullname').val('');
    $('#txtemail').val('');
    $('#txtcontent').val('');
    $('#recaptcha_response_field').val('');
    return;
}
var RecaptchaOptions = {
    theme : 'custom',
    custom_theme_widget: 'recaptcha_widget'
};
/** contact form */

/* support form */
function submit_support(){
    if($('#txttitle').val()== ''){
        tggv_form_alert('txttitle', 'Vui lòng nhập tiêu đề');
        return;
    }
    if(!validateEmail($('#txtemail').val())){
        tggv_form_alert('txtemail', 'Vui lòng nhập 1 email hợp lệ');
        return;
    }
    if($('#recaptcha_response_field').val() == ''){
        tggv_form_alert('recaptcha_response_field', 'Vui lòng nhập mã bảo vệ bạn nhìn thấy trong hình bên dưới');
        return;
    }
    $('#frmSupport').submit();
}
function reset_support(){
    $('#txttitle').val('');
    $('#txtemail').val('');
    $('#txtcontent').val('');
    $('#recaptcha_response_field').val('');
    return;
}
/* support form */


/* search google */
function submit_search(){
    if(!$('#quick-search-input').attr('id')){
        return;
    }
    if($('#quick-search-input').val() == ''){
        tggv_form_alert('quick-search-input', 'Vui lòng nhập 1 từ khóa');
        return;
    }
    $('#searchform').submit();
}

/** poll */
function vote_poll(){
    var option_selected =   $(".poll-row input:checked");
    if(!$(option_selected).attr('id')){
        alert('Vui lòng chọn 1 lựa chọn!');
        return;
    }
    $.ajax({
          type: 'POST',
          data: {optionid: $(option_selected).val()},
          dataType: 'html',
          url: baseUrl + '/polls/vote',
          success: function(data) {
             if(data == '1'){
                alert('Bạn đã bình chọn thành công');
             }else{
                 alert('Bạn đã bình chọn rồi!');
             }
          }
    });
}


function setHomepage()
{
    if (document.all)
    {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage(baseUrl);
    }
    else if (window.sidebar)
    {
        if (window.netscape)
        {
            try
            {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch(e)
            {
                return;
            }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage', baseUrl);
    }
}
/* set bookmark */
function setBookmark(){
	if(document.all){
		window.external.AddFavorite(location.href,document.title);
	}else if(window.sidebar){
		window.sidebar.addPanel (document.title,location.href,'');
	}
	else if(window.chrome){
    	alert('dùng phím tắt ctrl+D để bookmark (Command+D cho macs) sau đó click Ok');
    }
}
/* set bookmark */

/* slideshow new game */
var lastestgame_record_index =   0;
var int_lastestgame     =   null;

function auto_slideshow_lastestgame(){
    var list_lastestgame = $.makeArray($('.list-lastest-news'));
    if(list_lastestgame.length <= 1){
        return;
    }
    if(lastestgame_record_index > list_lastestgame.length - 1){
        lastestgame_record_index = 0;
    }
    $('.list-lastest-news').hide();
    $(list_lastestgame[lastestgame_record_index]).fadeIn(800);
    lastestgame_record_index++;
    int_lastestgame = setTimeout(function(){
        auto_slideshow_lastestgame();
    },5000);
}
/*slide show new game */



/* slideshow hot game */
var hotgame_record_index =   0;
var int_hotgame     =   null;
function auto_slideshow_hotgame(){
    var list_hotgame = $.makeArray($('.top-game .list-game'));
    if(list_hotgame.length <= 1){
        return;
    }
    if(hotgame_record_index > list_hotgame.length - 1){
        hotgame_record_index = 0;
    }
    $('.top-game .list-game').hide();
    $(list_hotgame[hotgame_record_index]).fadeIn(800);
    hotgame_record_index++;
    int_hotgame = setTimeout(function(){
        auto_slideshow_hotgame();
    },15000);
}
function slideshow_hotgame_next(){
    clearTimeout(int_hotgame);
    var list_hotgame = $.makeArray($('.top-game .list-game'));
    if(hotgame_record_index >= list_hotgame.length){
        hotgame_record_index = 0;
    }
    auto_slideshow_hotgame();
}
function slideshow_hotgame_pre(){
    hotgame_record_index--;
	hotgame_record_index--;
    clearTimeout(int_hotgame);
    var list_hotgame = $.makeArray($('.top-game .list-game'));
    if(hotgame_record_index < 0){
        hotgame_record_index = 0;
    }
    auto_slideshow_hotgame();
}
/* end slideshow hot game */

/* load game hay nhat cho 1 danh muc khi click vao tab */
function loadHotgamebycategoryAjax(catid, current_li){
	var tab_class           =	'tab-block-' + catid;
	var gamelist_class	=	'home-block-' + catid;
	var layer_idname	=	'layerid-' + catid;

        show_screen_loader_ajax(gamelist_class, layer_idname);
        
	var li_tabs = $('.' + tab_class).find('li');
	$(li_tabs).each(function(index, el){
		if($(el).hasClass('active')){
			$(el).removeClass('active');
		}
	});
	$(current_li).addClass('active');
        $.ajax({
          type: 'GET',
          dataType: 'html',
          url: baseUrl + '/games/service_get_hotgameincat/catid:' + catid,
          success: function(data) {
             if(data != '0'){
                $('.' + gamelist_class).html(data);

             }
          }
        });
        close_screen_loader_ajax(layer_idname);
}
/* load game moi nhat cho 1 danh muc khi click vao tab */
function loadLastestgamebycategoryAjax(catid, current_li){
	var tab_class           =	'tab-block-' + catid;
	var gamelist_class	=	'home-block-' + catid;
	var layer_idname	=	'layerid-' + catid;

        show_screen_loader_ajax(gamelist_class, layer_idname);
        
	var li_tabs = $('.' + tab_class).find('li');
	$(li_tabs).each(function(index, el){
		if($(el).hasClass('active')){
			$(el).removeClass('active');
		}
	});
	$(current_li).addClass('active');
        $.ajax({
          type: 'GET',
          dataType: 'html',
          url: baseUrl + '/games/service_get_lastestgameincat/catid:' + catid,
          success: function(data) {
             if(data != '0'){
                $('.' + gamelist_class).html(data);

             }
          }
        });
        close_screen_loader_ajax(layer_idname);
        
}
/* load game nhieu nguoi choi nhat cho 1 danh muc khi click vao tab */
function loadPopulargamebycategoryAjax(catid, current_li){
	var tab_class           =	'tab-block-' + catid;
	var gamelist_class	=	'home-block-' + catid;
	var layer_idname	=	'layerid-' + catid;

	show_screen_loader_ajax(gamelist_class, layer_idname);

	var li_tabs = $('.' + tab_class).find('li');
	$(li_tabs).each(function(index, el){
		if($(el).hasClass('active')){
			$(el).removeClass('active');
		}
	});
	$(current_li).addClass('active');

        $.ajax({
          type: 'GET',
          dataType: 'html',
          url: baseUrl + '/games/service_get_populargameincat/catid:' + catid,
          success: function(data) {
             if(data != '0'){
                $('.' + gamelist_class).html(data);
             }
          }
        });
        close_screen_loader_ajax(layer_idname);
}

function show_screen_loader_ajax(classname_blockgame, id){
	var width	=	$('.' + classname_blockgame).width();
	var height	=	$('.' + classname_blockgame).height();
	var offset	=	$('.' + classname_blockgame).offset();

	var html	=	'<div class="ajax_loader_layer" id="'+ id + '"><img src="/img/input-loading.gif" /></div>';
	$('body').append(html);
	$('#' + id).find('img').css({
		'left': (width/2) - 12,
		'top': (height/2) - 12
	});
	$('#' + id).css({
		'width' : width,
		'height' : height,
		'display': 'block',
		'left': offset.left,
                'position': 'absolute',
		'top': offset.top
	});
}
function close_screen_loader_ajax(id){
	$('#' + id).remove();
}

window.onload = function(){
	$(document).ready(function(){
            refesh_favouriteList();
            if($(".like-facebook").attr('class')){
                move_likefacebook_icon();
            }
            move_facebook_fanpage();
            
            if(screen.width < 1280){
                $('body').width(1280);
            }else{
                $('body').width(screen.width);
            }
            if($('.top-game .list-game').attr('class')){
                auto_slideshow_hotgame();
            }
            if($('.list-lastest-news').attr('class')){
                auto_slideshow_lastestgame();
            }
            //croll
            if($(document).scrollTop() > 0){
                $('.linkTop').fadeIn();
            }else{
                $('.linkTop').fadeOut();
            }
            if($('#_adb_22_10002366').attr('id')){
                $('#_adb_22_10002366').css({
                    'left': '0px',
                    'top': '30px'
                });
            }
            if($('#_adb_22_10002367').attr('id')){
                $('#_adb_22_10002367').css({
                    'right': '0px',
                    'top': '30px'
                });
            }            
            $(window).scroll(function(){
                if($(document).scrollTop() > 0){
                    $('.linkTop').fadeIn();
                }else{
                    $('.linkTop').fadeOut();
                }
            });
	});
};

 //croll to top
function scrolltotop(){
    var current_pos =   $(document).scrollTop();
    var int_val;
    move();
    function move(){
        if(current_pos <= 0){
            $(document).scrollTop(0);
            clearTimeout(int_val);
            return;
        }
        $(document).scrollTop(current_pos);
        int_val =   setTimeout(function(){
            current_pos =   current_pos - 35;
            move();
        }, 5);
    }
}

/** move icon facebook */

function move_likefacebook_icon(){
   $(".like-facebook-temp").css("display", "none");     
   $(".like-facebook").height(21);
   $(".like-facebook").width(140);
   var postition = $(".like-facebook").offset();
   var top = postition.top + "px";
   var left = postition.left - 15 + "px";
   $(".like-facebook-temp").css("left", left);
   $(".like-facebook-temp").css("top", top);
   $(".like-facebook-temp").css("background-color", '#fff');
   $(".like-facebook-temp").css("position", "absolute");
   $(".like-facebook-temp").css("display", "block")

}
/** move icon facebook fanpage */
function move_facebook_fanpage(){
   $(".findusfacebook_block_temp").css("display", "none");
   $(".findusfacebook_block").height(270);
   $(".findusfacebook_block").width(250);
   var postition = $(".findusfacebook_block").offset();
   var top = postition.top + "px";
   var left = postition.left + 10 + "px";
   
   $(".findusfacebook_block_temp").css("left", left);
   $(".findusfacebook_block_temp").css("top", top);
   $(".findusfacebook_block_temp").css("background-color", '#fff');
   $(".findusfacebook_block_temp").css("position", "absolute");
   $(".findusfacebook_block_temp").css("display", "block")
}

/** popup login **/
function showPopupLogin(){
    var document_w   =   $(window).width();
    var document_h   =   $(window).height();
    var popup_w      =   $('.popup-login').width();
    var popup_h      =   $('.popup-login').height();
    if($('.popup-login').attr('class')){
        $('.popup-login').css({
            'left': document_w/2 - popup_w/2,
            'top': document_h/2 - popup_h/2
        });
    }
    show_screen_waitting();
    $('.popup-login').show();
}
function closePopuplogin(){
    $('.popup-login').fadeOut(500, function(){
        close_screen_waitting();
    });
}

/** comment */
function submit_comment(){
        var fullname_clear  =   $('#your-full-name').attr('clear');
        if(fullname_clear == '0' || (fullname_clear == '1' && $('#your-full-name').val() == '')) {
            alert('Vui lòng nhập tên hiển thị của bạn!');
            $('#your-full-name').attr('clear', '0');
            $('#your-full-name').val('Tên hiển thị');
            return;
        }
        var commentContent_clear  =   $('#your-comment-input').attr('clear');
        if(commentContent_clear == '0' || (commentContent_clear == '1' && $('#your-comment-input').val() == '')) {
            alert('Vui lòng nhập ý kiến của bạn!');
            $('#your-comment-input').attr('clear', '0');
            $('#your-comment-input').val('Nhập ý kiến của bạn cho game này');
            return;
        }

        var data    =   {
            'data[Comment][your-comment]': $('#your-comment-input').val(),
            'data[Comment][game_id]': $('#CommentGameId').val(),
            'data[Comment][full-name]': $('#your-full-name').val(),
            'data[_Token][key]': $('#frmComment [name="data[_Token][key]"]').val(),
            '_method': $('#frmComment [name="_method"]').val(),
            'data[_Token][fields]': $('#frmComment [name="data[_Token][fields]"]').val()
        };
        $.ajax({
          type: 'POST',
          dataType: 'json',
          data: data,
          url: baseUrl + '/comments/post',
          success: function(data) {
              if(data != '0'){
                insertComment(data);
              }else{
                  alert('Vui lòng nhấn F5 tải lại trang và tiếp tục comment bạn nhé!');
              }
          }
        });
}
function insertComment(data){
    var comments    =   $.makeArray('.comment-rows');
    var bgclass     =   'bg1';
    if($(comments[0]).hasClass('bg1')){
        bgclass =   'bg2';
    }
    var html    =   '<div style="display:none;" id="preview_comment" class="comment-rows ' + bgclass +'">';
    html    +=  '<img width="50px" height="50px" alt="no avatar" src="/img/no-avatar.jpg">';
    html    +=  '<div class="comment-rows-content"><p><strong>' + data.fullname + '</strong>';
    html    +=  '<span>Gởi lúc ' + data.created + '</span></p><p class="comment-content">' + data.content + '</p></div></div>';
    $('.comment-list').prepend(html);
    $.scrollTo('.comment-list', function(){
        $('#preview_comment').fadeIn(1000);
    });
}
function comment_clearContent(object){
    if($(object).attr('clear') == '0'){
        $(object).val('');
        $(object).attr('clear', '1');
    }
}
/**
*
*  Base64 encode / decode
*
**/
var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

